<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入收货人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label-width="90px" label="收货手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入收货手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入收货地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货状态" prop="shipmentsStatus">
        <el-select v-model="queryParams.shipmentsStatus" placeholder="请选择发货状态" clearable>
          <el-option
            v-for="dict in dict.type.shouhuo_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="number" width="200px" />
      <el-table-column label="用户名称" align="center" prop="userName" width="100px"/>
      <el-table-column label="收货人" align="center" prop="name" />
      <el-table-column label="收货手机号" align="center" prop="phone" width="120px" />
      <el-table-column label="收货地址" align="center" prop="address" width="200px"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发货状态" align="center" prop="shipmentsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.shouhuo_status" :value="scope.row.shipmentsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="150px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['order:order:edit']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.order_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发货状态" prop="shipmentsStatus">
          <el-radio-group v-model="form.shipmentsStatus">
            <el-radio
              v-for="dict in dict.type.shouhuo_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 订单明细对话框 -->
    <el-dialog :title="title" :visible.sync="openXq" width="500px" append-to-body>
      <el-divider content-position="center">订单基础信息</el-divider>
          <label>订单编号: {{form.number}}</label>
      <br>
          <label >用户名称: {{form.userName}}</label>
          <br>
          <label>收货人: {{form.name}}</label>
      <br>
          <label >收货手机号: {{form.phone}}</label>
      <br>
          <label >收货地址: {{form.address}}</label>
          <br>
          <label v-if="form.status === 0">支付状态: 未支付</label>

          <label v-else>支付状态: 已支付</label>
      <br>
          <label v-if="form.status === 0">发货状态: 未发货</label>
          <label v-else >发货状态: 已发货</label>
          <br>
      <label>合计: {{this.AllTotalPrice}}元</label>
      <br>
      <label>实付: {{form.actualPrice}}元</label>
      <br>
          <label>创建时间: {{form.createTime}}</label>
      <br>
      <label>更新时间: {{form.updateTime}}</label>
        <el-divider content-position="center">订单明细信息</el-divider>
        <el-table :data="orderDetailList" :row-class-name="rowOrderDetailIndex" @selection-change="handleOrderDetailSelectionChange" ref="orderDetail">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品名称" prop="name" width="100"></el-table-column>
          <el-table-column label="图片" align="center" prop="picture" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.picture" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="80"></el-table-column>
          <el-table-column label="数量" prop="amount" width="50"></el-table-column>
          <el-table-column label="总额" prop="totalPrice" width="80"></el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";

export default {
  name: "Order",
  dicts: ['shouhuo_status', 'order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedOrderDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      // 订单明细表格数据
      orderDetailList: [],
      //
      AllTotalPrice: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openXq: false,
      // 更新时间时间范围
      daterangeCreateTime: [],
      // 更新时间时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: null,
        userId: null,
        createTime: null,
        updateTime: null,
        addressId: null,
        status: null,
        shipmentsStatus: null,
        phone: null,
        userName: null,
        name: null,
        address: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        number: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        addressId: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "订单状态 0 未支付 1已支付不能为空", trigger: "change" }
        ],
        shipmentsStatus: [
          { required: true, message: "发货状态: 0未发货 1已发货不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        userId: null,
        createTime: null,
        updateTime: null,
        addressId: null,
        status: null,
        shipmentsStatus: null
      };
      this.orderDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.orderDetailList = response.data.orderDetailList;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    handleDetail(row) {
      this.reset();
      this.AllTotalPrice = 0;
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.orderDetailList = response.data.orderDetailList;
        for (let i = 0; i < this.orderDetailList.length; i++) {
          const s = this.orderDetailList[i];
          this.AllTotalPrice += s.totalPrice
        }
        this.openXq = true;
        this.title = "订单明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.orderDetailList = this.orderDetailList;
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单管理编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 订单明细序号 */
    rowOrderDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 订单明细添加按钮操作 */
    handleAddOrderDetail() {
      let obj = {};
      obj.productId = "";
      obj.amount = "";
      obj.totalPrice = "";
      obj.createTime = "";
      obj.updateTime = "";
      this.orderDetailList.push(obj);
    },
    /** 订单明细删除按钮操作 */
    handleDeleteOrderDetail() {
      if (this.checkedOrderDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的订单明细数据");
      } else {
        const orderDetailList = this.orderDetailList;
        const checkedOrderDetail = this.checkedOrderDetail;
        this.orderDetailList = orderDetailList.filter(function(item) {
          return checkedOrderDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleOrderDetailSelectionChange(selection) {
      this.checkedOrderDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
